package com.idanchuang.component.mybatis.plus.warmup;

import com.idanchuang.sun.client.common.health.WarmUp;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 *
 * 组件预热 (非必要代码)
 *
 * @author yjy
 * Created at 2022/2/11 5:16 下午
 */
public class WarmUpMybatis {

    private static final Logger logger = LoggerFactory.getLogger(WarmUpMybatis.class);

    private final List<SqlSessionFactory> sqlSessionFactories;

    public WarmUpMybatis(List<SqlSessionFactory> sqlSessionFactories) {
        this.sqlSessionFactories = sqlSessionFactories;
    }

    @WarmUp(concurrent = 10, total = 100)
    public void warm() throws SQLException {
        for (SqlSessionFactory sqlSessionFactory : sqlSessionFactories) {
            Connection connection = sqlSessionFactory.openSession().getConnection();
            ResultSet rs = connection.prepareStatement("select now()").executeQuery();
            if (rs.next()) {
                String data = rs.getString(1);
                logger.debug("select now() > " + data);
            }
            if (!connection.getAutoCommit()) {
                connection.commit();
            }
            connection.close();
        }
    }

}
